package com.jsb.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.annotation.SystemControllerLog;
import com.jsb.common.config.Global;
import com.jsb.common.utils.BeanUtils;
import com.jsb.common.utils.StringUtils;
import com.jsb.dto.UserDealRecordDetail;
import com.jsb.dto.WithdrawDto;
import com.jsb.model.User;
import com.jsb.model.UserDealRecordExample;
import com.jsb.model.Withdraw;
import com.jsb.model.WithdrawExample;
import com.jsb.model.WithdrawExample.Criteria;
import com.jsb.service.UserDealRecordService;
import com.jsb.service.UserService;
import com.jsb.service.WithdrawService;
import com.jsb.wx.po.WxEnterpriseRes;
import com.jsb.wx.util.PayCommonUtil;

@Controller
public class WithdrawController{
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/withdraw/list.do";
	
	@Resource
	private WithdrawService withdrawService;
	@Resource
	private UserService userService;
	@Resource
	private UserDealRecordService userDealRecordService;
	
	@RequestMapping("/withdraw/list")
	public String list(
			Model model,String phone,String status,String type,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		WithdrawExample withdrawExample = new WithdrawExample();
		if(StringUtils.isEmpty(phone)){
			if(StringUtils.isNotEmpty(status)){
				Criteria createCriteria = withdrawExample.createCriteria();
				if(status.equals(PayCommonUtil.PAYSUCCESS_STATUS) || status.equals(PayCommonUtil.PAY_DISAGREE_CODE)||status.equals(PayCommonUtil.PAYPENDING_STATUS)){
					createCriteria.andStatusEqualTo(status);
				}else{
					createCriteria.andStatusNotEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
					createCriteria.andStatusNotEqualTo(PayCommonUtil.PAY_DISAGREE_CODE);
					createCriteria.andStatusNotEqualTo(PayCommonUtil.PAYPENDING_STATUS);
				}
			}
		}else{
			List<User> userByLikePhone = userService.getUserByLikePhone(phone);
			for (User user : userByLikePhone) {
				String userid = user.getPhoneNumber();
				Criteria createCriteria = withdrawExample.createCriteria();
				if(StringUtils.isNotBlank(userid)){
					createCriteria.andPhoneNumLike("%"+userid+"%");
				}
				if(StringUtils.isNotEmpty(status)){
					if(status.equals(PayCommonUtil.PAYSUCCESS_STATUS) || status.equals(PayCommonUtil.PAY_DISAGREE_CODE)||status.equals(PayCommonUtil.PAYPENDING_STATUS)){
						createCriteria.andStatusEqualTo(status);
					}else{
						createCriteria.andStatusNotEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
						createCriteria.andStatusNotEqualTo(PayCommonUtil.PAY_DISAGREE_CODE);
						createCriteria.andStatusNotEqualTo(PayCommonUtil.PAYPENDING_STATUS);
					}
				}
				withdrawExample.or(createCriteria);
			}
		}
		int totalCount = withdrawService.countWithdraw(withdrawExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		withdrawExample.setPageIndex((pageNum - 1) * pageSize);
		withdrawExample.setPageSize(pageSize);
		withdrawExample.setOrderByClause("createDate desc");
		List<Withdraw> withdraws1 = withdrawService.getPageWithdraw(withdrawExample);
		List<WithdrawDto> withdraws = new ArrayList<WithdrawDto>();
		for (Withdraw withdraw : withdraws1) {
			String phoneNum = withdraw.getPhoneNum();
			User userByPhoneNumber = userService.getUserByPhoneNumber(phoneNum);
			WithdrawDto dto = new WithdrawDto();
			BeanUtils.copyProperties(dto, withdraw);
			dto.setUser(userByPhoneNumber);
			withdraws.add(dto);
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("withdraws", withdraws);
		model.addAttribute("phone", phone);
		model.addAttribute("type", type);
		model.addAttribute("status", status);
		return "/Withdraw/list";
	}
	
	@RequestMapping("/withdraw/toAdd")
	public String toAdd(Model model) {
		return "/Withdraw/add";
	}

	@RequestMapping("/withdraw/add")
	public String add(Model model, @ModelAttribute("withdraw") Withdraw withdraw) {
		withdrawService.addWithdraw(withdraw);
		return redirect;
	}

	@RequestMapping("/withdraw/del")
	public String del(Model model,
			@RequestParam(value = "uuid", required = true) String uuid) {
		withdrawService.delWithdrawByUuid(uuid);
		return redirect;
	}

	@RequestMapping("/withdraw/toEdit")
	public String toEdit(Model model,
			@RequestParam(value = "uuid", required = true) String uuid) {
		Withdraw withdraw = withdrawService.getWithdrawByUuid(uuid);
		model.addAttribute("withdraw", withdraw);
		return "/Withdraw/edit";
	}

	@RequestMapping("/withdraw/edit")
	public String edit(Model model, @ModelAttribute("withdraw") Withdraw withdraw) {
		withdrawService.updateWithdraw(withdraw);
		return redirect;
	}

	@RequestMapping("/withdraw/view")
	public String view(Model model,
			@RequestParam(value = "uuid", required = true) String uuid) {
		Withdraw withdraw = withdrawService.getWithdrawByUuid(uuid);
		model.addAttribute("withdraw", withdraw);
		return "/Withdraw/view";
	}
	/**
	 * 同意提现
	 * @param withdraw1
	 * @return
	 */
	@RequestMapping("/withdraw/agreeWithdraw")
	@RequiresRoles(value = { "admin","customer" },logical = Logical.OR)
	@ResponseBody
	@SystemControllerLog(description = "审核提现同意")
	public Object agreeWithdraw(Model model,@ModelAttribute("withdraw") Withdraw withdraw1){
		WxEnterpriseRes res = new WxEnterpriseRes();
		String uuid = withdraw1.getUuid();
		Withdraw withdrawByUuid = withdrawService.getWithdrawByUuid(uuid);
		String status = withdrawByUuid.getStatus();
		if(status.equals(PayCommonUtil.PAYSUCCESS_STATUS)){
			res.setCode(Global.FALSE);
			res.setDes("该次提现已成功，不能再次审核!");
			return res;
		}
		if(status.equals(PayCommonUtil.PAY_DISAGREE_CODE)){
			res.setCode(Global.FALSE);
			res.setDes("该次提现已拒绝，不能再次审核!");
			return res;
		}
		res = withdrawService.updatePayEnterprise(withdraw1);
		return res;
	}
	/**
	 * 不同意提现
	 * @param withdraw1
	 * @return
	 */
	@RequestMapping("/withdraw/disagreeWithdraw")
	@RequiresRoles(value = { "admin","customer" },logical = Logical.OR)
	@SystemControllerLog(description = "审核提现不同意")
	@ResponseBody
	public Object disagreeWithdraw(Model model,@ModelAttribute("withdraw") Withdraw withdraw1){
		WxEnterpriseRes res = new WxEnterpriseRes();
		String uuid = withdraw1.getUuid();
		String remarks = withdraw1.getRemarks();
		Withdraw withdrawByUuid = withdrawService.getWithdrawByUuid(uuid);
		String status = withdrawByUuid.getStatus();
		if(status.equals(PayCommonUtil.PAYSUCCESS_STATUS)){
			res.setCode(Global.FALSE);
			res.setDes("该次提现已成功，不能再次审核!");
			return res;
		}
		if(status.equals(PayCommonUtil.PAY_DISAGREE_CODE)){
			res.setCode(Global.FALSE);
			res.setDes("该次提现已拒绝，不能再次审核!");
			return res;
		}
		if(StringUtils.isEmpty(remarks)){
			res.setCode(Global.FALSE);
			res.setDes("未填写原因。");
			return res;
		}
		Withdraw withdraw = new Withdraw();
		withdraw.setUuid(uuid);
		withdraw.setStatus(PayCommonUtil.PAY_DISAGREE_CODE);
		withdraw.setRemarks(remarks);
		withdrawService.updateWithdraw(withdraw);
		res.setCode(Global.TRUE);
		res.setDes("审核成功。");
		return res;
	}
	
	@RequestMapping("/withdraw/moneyDetail")
	public String moneyDetail(Model model,
			@RequestParam(value = "uuid", required = true) String uuid){
		Withdraw withdrawByUuid = withdrawService.getWithdrawByUuid(uuid);
		String phoneNum = withdrawByUuid.getPhoneNum();
		List<Withdraw> lastRecord = getLastRecord(phoneNum);
		Date sucDate = null;
		if(null != lastRecord && lastRecord.size()>0){
			sucDate = lastRecord.get(0).getSucDate();
		}else{
			Calendar calendar = Calendar.getInstance(); 
			calendar.set(2016, 05, 05, 00, 00, 00);
			sucDate = calendar.getTime();
		}
		  Map<String,Object> map = new HashMap<String, Object>();
		  map.put("userId", phoneNum);
		  map.put("status", PayCommonUtil.PAYSUCCESS_STATUS);
		  map.put("tradeType", "2");
		  map.put("createDate", sucDate);
		  map.put("goodsType", "4");
		  List<UserDealRecordDetail> userDealRecordDetails = withdrawService.redPacketDetail(map);
		  model.addAttribute("userDealRecordDetails", userDealRecordDetails);
		  model.addAttribute("uuid", uuid);
		  return "/Withdraw/userDealRecordDetail";
	}
	
	/**
	 * 某用户最后一次提现记录
	 * @param phone
	 * @return
	 */
	public List<Withdraw> getLastRecord(String phone){
		WithdrawExample example = new WithdrawExample();
		Criteria criteria = example.createCriteria();
		criteria.andPhoneNumEqualTo(phone);
		criteria.andStatusEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
		example.setOrderByClause("createDate DESC");
		example.setPageSize(1);
		return withdrawService.getPageWithdraw(example );
	}
}
